<?php
namespace sef;
use sef;

class db {

	public function __construct() {
		$config = new config();
		$this -> db_host = $config -> db_host;
		$this -> db_name = $config -> db_name;
		$this -> db_user = $config -> db_user;
		$this -> db_password = $config -> db_password;
		$this -> table_prefix = $config -> table_prefix;
		$this -> connect();
	}

	private function connect() {
		try {
			$dsn = "mysql:host={$this -> db_host};dbname={$this -> db_name}";
			$conn = new \PDO($dsn, $this -> db_user, $this -> db_password);
			// 设置为异常模式
			$conn -> setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
			$conn -> query('set names utf8;');
			$this -> connect = $conn;
		} catch(PDOException $e) {
			echo "Error:" . $e;
		};
	}

	public function execute($sql, $parameters = null) {
		$conn = $this -> connect;
		$statement = $conn -> prepare($sql);
		$statement -> setFetchMode(\PDO::FETCH_ASSOC);
		$statement -> execute($parameters);
		$affected_rows = $statement -> rowcount();
		$statement = null;
		$conn = null;
		return $affected_rows;
	}

	public function query($sql, $parameters = null) {
		$conn = $this -> connect;
		$statement = $conn -> prepare($sql);
		$statement -> setFetchMode(\PDO::FETCH_ASSOC);
		$statement -> execute($parameters);
		$rs = $statement -> fetchAll();
		$statement = null;
		$conn = null;
		return $rs;
	}

	public function get_db_fields($table_name) {
		$fields = array();
		$sql = 'show columns from ' . $table_name;
		$statement = $this -> connect -> prepare($sql);
		$statement -> setFetchMode(\PDO::FETCH_ASSOC);
		$statement -> setFetchMode(\PDO::CASE_LOWER);
		$statement -> execute();

		$rs = $statement -> fetchAll();
		$statement = null;
		$conn = null;
		$rs = rotate($rs, 'Field');
		return $rs;
	}

	public function get_last_id() {
		return $this -> connect -> lastInsertId();
	}

}
